package org.example.security.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.example.db.entity.Permission;
import org.example.db.entity.User;
import org.example.db.entity.WxUser;
import org.example.db.mapper.UserMapper;
import org.example.db.mapper.WxUserMapper;
import org.example.security.bo.SecurityUserDetails;
import org.example.security.bo.SecurityWxUserDetails;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service("SecurityWxUserDetailsService")
public class SecurityWxUserDetailsService implements UserDetailsService {


    WxUserMapper wxUserMapper;
    PermissionService permissionService;

    public SecurityWxUserDetailsService(WxUserMapper wxUserMapper, PermissionService permissionService) {
        this.wxUserMapper = wxUserMapper;
        this.permissionService = permissionService;
    }

    @Override
    public UserDetails loadUserByUsername(String idStr) throws UsernameNotFoundException {

        WxUser user = this.getWxUserByUsername(idStr);
        if(user != null){
            //log.info("用户 {} 生成UserDetails ", user.getNickname());
            List<Permission> permissionList = permissionService.getPermissionListByWxUserId(user.getId());
            return new SecurityWxUserDetails(user, permissionList);
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }

    public WxUser getWxUserByUsername(String idStr){

        long id = Long.parseLong(idStr);
        List<WxUser> userList = wxUserMapper.selectList(new QueryWrapper<WxUser>().lambda().eq(WxUser::getId, id));

        return userList.get(0);
    }
}
